# coding: utf-8

from leancloud import Object
from leancloud import Query
from leancloud import LeanCloudError
from flask import Blueprint
from flask import request
from flask import redirect
from flask import url_for
from flask import render_template

class Games(Object):
    pass

class _User(Object):
    pass

debug_view = Blueprint('debug', __name__)

@debug_view.route('')
def show():
    """
    显示游戏列表
    """
    try:
        games = Query(Games).descending('createdAt').find()
    except LeanCloudError as e:
        if e.code == 101:  # 服务端对应的 Class 还没创建
            games = []
        else:
            raise e
    return render_template('debug.html', games=games)


@debug_view.route('', methods=['POST'])
def add():
    """
    增加新游戏
    """
    gameName = request.form['gameName']
    describe = request.form['describe']
    
    games = Games()
    games.set('gameName', gameName)
    games.set('describe', describe)
    try:
        games.save()
    except LeanCloudError as e:
        return e.error, 502
    return redirect(url_for('debug.show'))


@debug_view.route('/addUser', methods=['GET'])
def addUser():
    """
    添加用户
    """
    userName = request.args.get("userName")
    pwd = request.args.get("pwd")
    _user = _User()
    _user.set('username', userName)
    _user.set('password', pwd)
    try:
        _user.save()
    except LeanCloudError as e:
        return e.error, 502
    return redirect(url_for('debug.show'))


